package com.example.backed.service.impl;

import com.example.backed.dto.GroupBuyCreateDTO;
import com.example.backed.dto.GroupBuyOrderCreateDTO;
import com.example.backed.dto.GroupBuyQueryDTO;
import com.example.backed.entity.GroupBuy;
import com.example.backed.entity.GroupBuyOrder;
import com.example.backed.mapper.GroupBuyMapper;
import com.example.backed.mapper.GroupBuyOrderMapper;
import com.example.backed.service.GroupBuyService;
import com.example.backed.vo.PageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class GroupBuyServiceImpl implements GroupBuyService {

    @Autowired
    private GroupBuyMapper groupBuyMapper;
    
    @Autowired
    private GroupBuyOrderMapper groupBuyOrderMapper;

    @Override
    @Transactional
    public GroupBuy create(GroupBuy groupBuy) {
        // 设置初始状态
        groupBuy.setJoinCount(0);
        if (groupBuy.getStartTime().isAfter(LocalDateTime.now())) {
            groupBuy.setStatus(0); // 未开始
        } else {
            groupBuy.setStatus(1); // 进行中
        }
        
        // 插入数据库
        groupBuyMapper.insert(groupBuy);
        return groupBuy;
    }

    @Override
    @Transactional
    public GroupBuy update(GroupBuy groupBuy) {
        // 更新数据库
        groupBuyMapper.update(groupBuy);
        return groupBuy;
    }

    @Override
    public GroupBuy findById(Long id) {
        return groupBuyMapper.findById(id);
    }

    @Override
    public List<GroupBuy> findOngoing() {
        return groupBuyMapper.findOngoing();
    }

    @Override
    public List<GroupBuy> findUpcoming() {
        return groupBuyMapper.findUpcoming();
    }

    @Override
    @Transactional
    public boolean updateStatus(Long id, Integer status) {
        return groupBuyMapper.updateStatus(id, status) > 0;
    }

    @Override
    @Transactional
    public boolean updateJoinCount(Long id, Integer delta) {
        return groupBuyMapper.updateJoinCount(id, delta) > 0;
    }

    @Override
    public List<GroupBuy> findAll() {
        return groupBuyMapper.findAll();
    }
    
    @Override
    public List<GroupBuy> findByStatus(Integer status) {
        return groupBuyMapper.findByStatus(status);
    }
    
    @Override
    @Transactional
    public void checkAndUpdateGroupBuyStatus() {
        LocalDateTime now = LocalDateTime.now();
        
        // 查找所有未开始的团购，如果开始时间已到，则更新为进行中
        List<GroupBuy> notStarted = groupBuyMapper.findByStatus(0);
        for (GroupBuy groupBuy : notStarted) {
            if (groupBuy.getStartTime().isBefore(now)) {
                groupBuyMapper.updateStatus(groupBuy.getId(), 1);
            }
        }
        
        // 查找所有进行中的团购，如果结束时间已到，则更新为已结束
        List<GroupBuy> ongoing = groupBuyMapper.findByStatus(1);
        for (GroupBuy groupBuy : ongoing) {
            if (groupBuy.getEndTime().isBefore(now)) {
                groupBuyMapper.updateStatus(groupBuy.getId(), 2);
                
                // 检查是否达到最低成团人数
                if (groupBuy.getJoinCount() >= groupBuy.getMinCount()) {
                    // 更新所有相关订单为已成团
                    groupBuyOrderMapper.updateOrderStatusByGroupBuyId(groupBuy.getId(), 1, 2);
                } else {
                    // 更新所有相关订单为未成团
                    groupBuyOrderMapper.updateOrderStatusByGroupBuyId(groupBuy.getId(), 1, 3);
                }
            }
        }
    }

    @Override
    @Transactional
    public GroupBuy createGroupBuy(GroupBuyCreateDTO createDTO) {
        GroupBuy groupBuy = new GroupBuy();
        BeanUtils.copyProperties(createDTO, groupBuy);
        
        return create(groupBuy);
    }

    @Override
    @Transactional
    public boolean cancelGroupBuy(Long id) {
        GroupBuy groupBuy = findById(id);
        if (groupBuy == null) {
            return false;
        }
        
        // 只有未开始或进行中的团购可以取消
        if (groupBuy.getStatus() != 0 && groupBuy.getStatus() != 1) {
            return false;
        }
        
        // 更新团购状态为已取消
        boolean success = updateStatus(id, 3);
        if (success) {
            // 更新所有相关订单为已取消
            groupBuyOrderMapper.updateOrderStatusByGroupBuyId(id, 0, 4); // 待支付订单取消
            groupBuyOrderMapper.updateOrderStatusByGroupBuyId(id, 1, 4); // 已支付待成团订单取消
        }
        
        return success;
    }

    @Override
    public GroupBuy getGroupBuyDetail(Long id) {
        return findById(id);
    }

    @Override
    public PageVO<GroupBuy> getGroupBuyList(GroupBuyQueryDTO queryDTO) {
        // 实现分页查询
        Integer pageNum = queryDTO.getPageNum();
        Integer pageSize = queryDTO.getPageSize();
        Integer status = queryDTO.getStatus();
        
        // 计算总数
        int total = groupBuyMapper.countByStatus(status);
        
        // 查询数据
        List<GroupBuy> list = groupBuyMapper.findByStatusWithPage(status, (pageNum - 1) * pageSize, pageSize);
        
        // 封装结果
        return new PageVO<>(list, total, pageNum, pageSize);
    }

    @Override
    @Transactional
    public GroupBuyOrder createOrder(Long userId, GroupBuyOrderCreateDTO createDTO) {
        // 查询团购活动
        GroupBuy groupBuy = findById(createDTO.getGroupBuyId());
        if (groupBuy == null || groupBuy.getStatus() != 1) {
            // 团购不存在或不是进行中状态
            return null;
        }
        
        // 检查用户是否已参与该团购
        GroupBuyOrder existOrder = groupBuyOrderMapper.findByUserAndGroupBuy(userId, createDTO.getGroupBuyId());
        if (existOrder != null) {
            // 用户已参与该团购
            return null;
        }
        
        // 检查购买数量是否超过限制
        if (createDTO.getQuantity() > groupBuy.getLimitPerUser()) {
            return null;
        }
        
        // 创建订单
        GroupBuyOrder order = new GroupBuyOrder();
        order.setGroupBuyId(createDTO.getGroupBuyId());
        order.setUserId(userId);
        order.setOrderNo(generateOrderNo());
        order.setQuantity(createDTO.getQuantity());
        order.setAmount(groupBuy.getGroupPrice().multiply(java.math.BigDecimal.valueOf(createDTO.getQuantity())));
        order.setStatus(1); // 直接设置为已支付待成团
        order.setAddress(createDTO.getAddress());
        order.setReceiver(createDTO.getReceiver());
        order.setPhone(createDTO.getPhone());
        order.setPayTime(LocalDateTime.now()); // 设置支付时间
        
        // 保存订单
        groupBuyOrderMapper.insert(order);
        
        // 更新团购参团人数
        updateJoinCount(createDTO.getGroupBuyId(), createDTO.getQuantity());
        
        // 检查是否达到最低成团人数
        groupBuy = findById(createDTO.getGroupBuyId()); // 重新查询最新数据
        if (groupBuy.getJoinCount() >= groupBuy.getMinCount()) {
            // 更新所有相关订单为已成团
            groupBuyOrderMapper.updateOrderStatusByGroupBuyId(groupBuy.getId(), 1, 2);
        }
        
        return order;
    }

    @Override
    @Transactional
    public boolean cancelOrder(Long userId, Long orderId) {
        GroupBuyOrder order = groupBuyOrderMapper.findById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            return false;
        }
        
        // 只有待支付的订单可以取消
        if (order.getStatus() != 0) {
            return false;
        }
        
        // 更新订单状态为已取消
        return groupBuyOrderMapper.updateStatus(orderId, userId, 4) > 0;
    }

    @Override
    public GroupBuyOrder getOrderDetail(Long userId, Long orderId) {
        GroupBuyOrder order = groupBuyOrderMapper.findById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            return null;
        }
        
        return order;
    }

    @Override
    public PageVO<GroupBuyOrder> getUserOrders(Long userId, Integer status, Integer pageNum, Integer pageSize) {
        // 计算总数
        int total = groupBuyOrderMapper.countByUserIdAndStatus(userId, status);
        
        // 查询数据
        List<GroupBuyOrder> list = groupBuyOrderMapper.findByUserIdAndStatusWithPage(userId, status, (pageNum - 1) * pageSize, pageSize);
        
        // 封装结果
        return new PageVO<>(list, total, pageNum, pageSize);
    }

    @Override
    @Transactional
    public boolean payOrder(Long userId, Long orderId) {
        GroupBuyOrder order = groupBuyOrderMapper.findById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            return false;
        }
        
        // 只有待支付的订单可以支付
        if (order.getStatus() != 0) {
            return false;
        }
        
        // 查询团购活动
        GroupBuy groupBuy = findById(order.getGroupBuyId());
        if (groupBuy == null || groupBuy.getStatus() != 1) {
            // 团购不存在或不是进行中状态
            return false;
        }
        
        // 更新订单状态为已支付待成团
        boolean success = groupBuyOrderMapper.updateStatus(orderId, userId, 1) > 0;
        if (success) {
            // 更新团购参团人数
            updateJoinCount(order.getGroupBuyId(), order.getQuantity());
            
            // 检查是否达到最低成团人数
            groupBuy = findById(order.getGroupBuyId()); // 重新查询最新数据
            if (groupBuy.getJoinCount() >= groupBuy.getMinCount()) {
                // 更新所有相关订单为已成团
                groupBuyOrderMapper.updateOrderStatusByGroupBuyId(groupBuy.getId(), 1, 2);
            }
        }
        
        return success;
    }
    
    /**
     * 生成订单编号
     */
    private String generateOrderNo() {
        return "GB" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 6);
    }
} 